﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Threading;
using Business.Entities.Configuration;
using Business.Entities.TFS;
using Data.ServiceAgents.Mailing;
using Data.ServiceAgents.TfsAccess;
using Data.ServiceAgents.ActiveDirectoryAccess;
using Data.DataAccess.Database;

namespace Business.Components.PendingChangesAlerts
{
    public class PendingChanges
    {
        protected ConfigurationProperties oConfigurationProperties;
        protected Dictionary<string, TFS_User> colTFS_User;
        protected EmailService oEmail;

        public PendingChanges(ConfigurationProperties oConfigurationProperties)
        {
            this.oConfigurationProperties = oConfigurationProperties;
            this.oEmail = new EmailService();
        }

        public void sendAlerts()
        {
            Thread.CurrentThread.CurrentCulture = new CultureInfo(this.oConfigurationProperties.Culture);
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(this.oConfigurationProperties.Culture);

            DbUserAccess oDbUserAccess = new DbUserAccess(this.oConfigurationProperties.ConnectionString);
            DbWorkspaceAccess oDbWorkspaceAccess = new DbWorkspaceAccess(this.oConfigurationProperties.ConnectionString);
            DbPendingChangeAccess oDbPendingChangeAccess = new DbPendingChangeAccess(this.oConfigurationProperties.ConnectionString);
            ActiveDirectory oActiveDirectory = new ActiveDirectory(this.oConfigurationProperties.AdDomain);

            this.colTFS_User = this.getPendingChanges();

            foreach (string str_user in colTFS_User.Keys)
            {
                TFS_User oTFS_User = colTFS_User[str_user];
                string str_log_body = string.Empty;
                int int_pending_changes_number = 0;

                TFS_USER oUser = oDbUserAccess.GetUser(oTFS_User.UserName);
                
                if (oUser == null)
                {
                    oUser = new TFS_USER();
                    oUser.USER_LOGIN = oActiveDirectory.getUser(oTFS_User.UserName);
                    oUser.USER_EMAIL = oActiveDirectory.getEmail(oTFS_User.UserName);
                    oDbUserAccess.AddUser(oUser);
                }
                else
                {
                    oUser.USER_EMAIL = oActiveDirectory.getEmail(oTFS_User.UserName);
                    oDbUserAccess.UpdateUser(oUser);
                }


                foreach (string str_workspace in oTFS_User.Workspaces.Keys)
                {
                    TFS_Workspace oTFS_Workspace = oTFS_User.Workspaces[str_workspace];

                    WORKSPACE oWorkspace = oDbWorkspaceAccess.GetWorkspace(oUser.USER_ID, oTFS_Workspace.WorkspaceName, oTFS_Workspace.Computer);

                    if (oWorkspace == null)
                    {
                        oWorkspace = new WORKSPACE();
                        oWorkspace.USER_ID = oUser.USER_ID;
                        oWorkspace.WORKSPACE_COMPUTER = oTFS_Workspace.Computer;
                        oWorkspace.WORKSPACE_NAME = oTFS_Workspace.WorkspaceName;
                        oWorkspace.WORKSPACE_TYPE = oTFS_Workspace.Type;
                        oDbWorkspaceAccess.AddWorkspace(oWorkspace);
                    }

                    int_pending_changes_number += oTFS_Workspace.PendingChanges.Count;

                    foreach (TFS_PendingChanges oTFS_PendingChanges in oTFS_Workspace.PendingChanges)
                    {
                        PENDING_CHANGE oPendingChange = new PENDING_CHANGE();
                        oPendingChange.WORKSPACE_ID = oWorkspace.WORKSPACE_ID;
                        oPendingChange.CHANGE_LOCAL_PATH = oTFS_PendingChanges.LocalFile;
                        oPendingChange.CHANGE_SERVER_PATH = oTFS_PendingChanges.ServerPath;
                        oPendingChange.CHANGE_CHECKOUT_DATE = oTFS_PendingChanges.CheckoutDate;
                        oPendingChange.CHANGE_TYPE = oTFS_PendingChanges.ChangeType;
                        oPendingChange.CHANGE_DATE = DateTime.Now;
                        oDbPendingChangeAccess.AddPendingChange(oPendingChange);

                        string str_log_line = string.Empty;
                        str_log_line += "RUTA EN EL SERVIDOR:   " + oTFS_PendingChanges.ServerPath + "\r\n";
                        str_log_line += "RUTA LOCAL:            " + oTFS_PendingChanges.LocalFile + "\r\n";
                        str_log_line += "FECHA DE CHECK-OUT:    " + oTFS_PendingChanges.CheckoutDate.ToLongDateString() + "\r\n";
                        str_log_line += "COMPUTADOR:            " + oTFS_Workspace.Computer + "\r\n";
                        str_log_line += "WORKSPACE:             " + oTFS_Workspace.WorkspaceName + "\r\n";

                        str_log_body += str_log_line + "\r\n";
                    }
                }

                if (this.oConfigurationProperties.LogPath.Length > 0)
                {
                    string str_log = this.oConfigurationProperties.LogPath + oUser.USER_LOGIN + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt";

                    // create a writer and open the file
                    TextWriter oTextWriter = new StreamWriter(str_log);

                    str_log_body = "El usuario " + oTFS_User.UserName + " tiene " + int_pending_changes_number + " cambios pendientes: \r\n\r\n" + str_log_body;

                    // write a line of text to the file
                    oTextWriter.Write(str_log_body);

                    // close the stream
                    oTextWriter.Close();
                }

                //if (this.oConfigurationProperties.SendEmails)
                //    this.oEmail.sendMail(this.oConfigurationProperties.AdministratorEmails, this.oConfigurationProperties.NotifyUsers, oTFS_User, str_log_body, int_index, int_length, str_log);
            }
        }

        public Dictionary<string, TFS_User> getPendingChanges()
        {
            SourceControl oSourceControl = new SourceControl(this.oConfigurationProperties.TfsServer);
            return oSourceControl.getPendingChangesByUsers();
        }

        private void sendMails()
        { 
        }
    }
}